package com.match.competition_sub.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.match.commonutils.JwtUtils;
import com.match.commonutils.MD5;
import com.match.commonutils.Result;
import com.match.competition_sub.client.MainClient;
import com.match.competition_sub.entity.Teacher;
import com.match.competition_sub.entity.vo.TeaQuery;
import com.match.competition_sub.service.TeacherService;
import com.match.entity.Vo.UserRoleVo;
import com.match.entity.roleEntity.CompetitionRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author AdiosF
 * @since 2021-09-21
 */
@Api(tags = "教师模块")
@RestController
@RequestMapping("/competition_sub/teacher")
public class TeacherController {
    //security密码加密
    BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private MainClient mainClient;


    @ApiOperation("通过EasyExcel添加教师数据")
    @PostMapping("/addTeaByExcel")
    public Result addTeacherByExcel(@RequestBody(required = false) MultipartFile file){
        //检验文件是否为空
        if (StringUtils.isEmpty(file)){
            return Result.error().message("请先选择好文件再上传");
        }
        //1.保存教师信息
        teacherService.addTeaByExcel(file,teacherService);
        //2.得到导入的所有教师
        List<Teacher> teacherList = teacherService.list(null);
        for (Teacher teacher : teacherList) {
            //2.存储教师角色
            Object roleList = mainClient.getOneRoleByQuery(teacher.getRole()).getData().get("role");
            String s = JSON.toJSONString(roleList);
            CompetitionRole competitionRole = JSON.parseObject(s, CompetitionRole.class);
            if (StringUtils.isEmpty(competitionRole)){
                //存储角色
                CompetitionRole competitionRole1=new CompetitionRole();
                competitionRole1.setRoleName(teacher.getRole());
                mainClient.addRole(competitionRole1);
                Object roleList1 = mainClient.getOneRoleByQuery(teacher.getRole()).getData().get("role");
                String s1 = JSON.toJSONString(roleList1);
                CompetitionRole competitionRole2 = JSON.parseObject(s1, CompetitionRole.class);
                //存储教师角色
                com.match.entity.Vo.UserRoleVo userRoleVo= new com.match.entity.Vo.UserRoleVo();
                userRoleVo.setRoleId(competitionRole2.getId());
                userRoleVo.setTeacherNumber(teacher.getNumber());
                //保存用户及其角色到数据库
                mainClient.userAddRole(userRoleVo);
                continue;
            }
            //存储教师角色
            com.match.entity.Vo.UserRoleVo userRoleVo= new com.match.entity.Vo.UserRoleVo();
            userRoleVo.setRoleId(competitionRole.getId());
            userRoleVo.setTeacherNumber(teacher.getNumber());
            //保存用户及其角色到数据库
            mainClient.userAddRole(userRoleVo);
        }
        return Result.ok().message("教师信息录入成功");
    }

    @ApiOperation("添加教师信息")
    @PostMapping("/addTeacher")
    public Result addTeacher(@ApiParam(required = true,value = "教师信息")
                        @RequestBody(required = true) Teacher teacher){
        //查询职工号是否重复
        QueryWrapper<Teacher> queryWrapper=new QueryWrapper<>();
        String number = teacher.getNumber();
        String phone = teacher.getPhone();
        if (!StringUtils.isEmpty(number)){
            queryWrapper.eq("number",number);
            Teacher teacherNumber = teacherService.getOne(queryWrapper);
            if (!StringUtils.isEmpty(teacherNumber)){
                return Result.error().message("职工号已存在");
            }
        }
        if (!StringUtils.isEmpty(phone)){
            QueryWrapper<Teacher> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("phone",phone);
            Teacher teacherPhone = teacherService.getOne(queryWrapper1);
            if (!StringUtils.isEmpty(teacherPhone)){
                return Result.error().message("电话号已存在");
            }
        }
        //向中间表添加该用户信息
        if (!StringUtils.isEmpty(teacher.getRole())){
            com.match.entity.Vo.UserRoleVo userRoleVo= new com.match.entity.Vo.UserRoleVo();
            userRoleVo.setRoleId(teacher.getRole());
            userRoleVo.setTeacherNumber(teacher.getNumber());
            //保存用户及其角色到数据库
            mainClient.userAddRole(userRoleVo);
        }else {
            //获取角色ID
            String roleName="教师";
            String roleId=teacherService.getRoleIdByName(roleName);
            com.match.entity.Vo.UserRoleVo userRoleVo= new com.match.entity.Vo.UserRoleVo();
            userRoleVo.setRoleId(roleId);
            userRoleVo.setTeacherNumber(teacher.getNumber());
            //保存用户及其角色到数据库
            mainClient.userAddRole(userRoleVo);
        }
        //设置用户角色
        if (!StringUtils.isEmpty(teacher.getRole())){
            teacher.setRole(teacherService.getRoleName(teacher.getRole()));
        }else {
            teacher.setRole("教师");
        }
        //对秘密进行加盐加密
        teacher.setPassword(passwordEncoder.encode(teacher.getPassword()));
        teacherService.save(teacher);
        return Result.ok().message("添加成功");
    }

    @ApiOperation("删除教师信息")
    @DeleteMapping("/deleteTeaByNum/{number}")
    public Result deleteTeaByNum(@ApiParam(required = true,value = "教师职工号")
                            @PathVariable(value = "number")String number){
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.eq("number",number);
        Teacher one = teacherService.getOne(teacherQueryWrapper);
        if (StringUtils.isEmpty(one)){
            return Result.error().message("不存在该教师");
        }
        teacherService.remove(teacherQueryWrapper);
        //移除中间表信息
        teacherService.removeUserAndRoleByNumber(number);
        return Result.ok().message("教师删除成功");
    }


    @ApiOperation("根据教师职工号查询教师")
    @GetMapping("/getTeaByNum/{number}")
    public Result getTeaByNum(@ApiParam(required = true,value = "教师职工号")
                         @PathVariable(value = "number")String number){
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.eq("number",number);
        Teacher one = teacherService.getOne(teacherQueryWrapper);
        if (StringUtils.isEmpty(one)){
            return  Result.error().message("教师不存在");
        }
        return Result.ok().data("teaInfo",one);
    }


    @ApiOperation("修改教师信息")
    @PostMapping("/updateTea")
    public Result updateTea(@RequestBody Teacher teacher){
        Teacher sqlTeacher = teacherService.getById(teacher.getId());
        //前端传过来的对象与数据库对比
        if(!sqlTeacher.equals(teacher)){
            //判断姓名是否发生了改变
            if (!sqlTeacher.getName().equals(teacher.getName())){
                //修改申请表中教师的姓名信息
                teacherService.updateCompetitionInfoTeacherName(teacher.getName(),teacher.getNumber());
            }
            //校验职工号是否重复
            if (!teacher.getNumber().equals(sqlTeacher.getNumber())){
                //封装教师的查询条件
                QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
                teacherQueryWrapper.eq("number",teacher.getNumber());
                int number = teacherService.count(teacherQueryWrapper);
                if (number==1){
                    return Result.error().message("职工号已存在");
                }
            }
            //校验手机号是否重复
            if (!teacher.getPhone().equals(sqlTeacher.getPhone())){
                //封装教师的查询条件
                QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
                teacherQueryWrapper.eq("phone",teacher.getPhone());
                int number = teacherService.count(teacherQueryWrapper);
                if (number==1){
                    return Result.error().message("手机号已存在");
                }
            }
            //密码发生改变
            if (!sqlTeacher.getPassword().equals(teacher.getPassword())){
                //对秘密进行加盐加密
                teacher.setPassword(passwordEncoder.encode(teacher.getPassword()));
            }
        }else {
            return Result.error().message("您暂未做任何修改");
        }
        teacherService.updateById(teacher);
        return Result.ok().message("信息修改成功");
    }


    @ApiOperation("条件查询教师数据")
    @PostMapping("/findTeaByQuery")
    public Result findTeaByQuery(@RequestBody(required = true) TeaQuery teaQuery){
        //封装查询条件
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        //检验条件是否为空
        String name = teaQuery.getName();
        String number = teaQuery.getNumber();
        if (StringUtils.isEmpty(name)&&StringUtils.isEmpty(number)){
            return Result.ok().message("请输入查询条件").data("list",null);
        }
        if (!StringUtils.isEmpty(name)){
            teacherQueryWrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(number)){
            teacherQueryWrapper.eq("number",number);
        }
        //返回时禁止密码返回
        teacherQueryWrapper.select(Teacher.class,i -> !i.getColumn().equals("password"));
        List<Teacher> list = teacherService.list(teacherQueryWrapper);
        if (list.isEmpty()){
            return Result.ok().message("此教师数据已被清空");
        }
        return Result.ok().message("查询成功").data("list",list);
    }


    @ApiOperation("查询所有教师")
    @GetMapping("/findAllTea")
    public Result findAllTea(){
        //返回时禁止密码返回
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.select(Teacher.class,i ->! i.getColumn().equals("password"));
        List<Teacher> list = teacherService.list(teacherQueryWrapper);
        if (list==null){
            return Result.error().message("暂无教师数据");
        }
        return Result.ok().data("list",list);
    }

    @ApiOperation("查询所有教师当做指导老师")
    @GetMapping("/getAllTeacherUseAdviser")
    public Result getAllTeacherUseAdviser(){
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.select("number,name");
        List<Teacher> list = teacherService.list(teacherQueryWrapper);
        return Result.ok().data("adviserOneList",list);
    }

    @ApiOperation("学生-查询所有的第一指导老师")
    @PostMapping("/getAllAdviser")
    public Result getAllAdviser(@RequestBody List<String> signUpList){
        Set<String> teacherNumberList=new HashSet<>();
        for (String s : signUpList) {
            teacherNumberList.add(s);
        }
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.in("number",teacherNumberList);
        teacherQueryWrapper.select("number,name");
        List<Teacher> teacherList = teacherService.list(teacherQueryWrapper);
        return Result.ok().data("teacherList",teacherList);
    }

    //TODO
    @ApiOperation("查询所有竞赛组织员")
    @GetMapping("/getAllTeacherByRole")
    public Result getAllTeacherByRole(){
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.eq("role","竞赛组织员").select("number,name");
        List<Teacher> list = teacherService.list(teacherQueryWrapper);
        QueryWrapper<Teacher> teacherQueryWrapper1=new QueryWrapper<>();
        teacherQueryWrapper1.eq("role","系统管理员").select("number,name");
        List<Teacher> list1 = teacherService.list(teacherQueryWrapper1);
        for (Teacher teacher : list1) {
            list.add(teacher);
        }
        if (list.isEmpty()){
            return Result.error().message("请添加竞赛组织员");
        }
        return Result.ok().data("AllOrganizer",list);
    }


    @ApiOperation("查询所有的教师部门")
    @GetMapping("/getAllTeacherDepartment")
    public Result getAllTeacherDepartment(){
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.select("distinct department");
        List<Teacher> list = teacherService.list(teacherQueryWrapper);
        if (list.isEmpty()){
            return Result.error().message("请添加教师部门");
        }
        List<Teacher> list1=new ArrayList<>();
        List<Teacher> list2=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String department = list.get(i).getDepartment();
            if (department.indexOf("系")>0){
                list1.add(list.get(i));
            }else {
                list2.add(list.get(i));
            }
        }
        List<Object> list3=new ArrayList<>();
        Map<String,Object> map=new HashMap<>();
        map.put("label","院组织");
        map.put("options",list2);
        Map<String,Object> map1=new HashMap<>();
        map1.put("label","系组织");
        map1.put("options",list1);
        list3.add(map);
        list3.add(map1);
        return Result.ok().data("AllDepartment",list3);
    }


    @ApiOperation("根据教师职工号更新教师角色")
    @PostMapping("/updateUserRoleByNumber")
    public Result updateUserRoleByNumber(@ApiParam(required = true)
                                    @RequestBody UserRoleVo userRoleVo){
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.eq("number",userRoleVo.getTeacherNumber());
        Teacher one = teacherService.getOne(teacherQueryWrapper);
        one.setRole(userRoleVo.getRoleId());
        boolean b = teacherService.updateById(one);
        return Result.ok().message("教师教师分配成功");
    }


    //TODO
    @ApiOperation("查询除教师以外的所有角色")
    @PostMapping ("/getTeacherRoleNotIn")
    public Result getTeacherRoleNotIn(@ApiParam(required = true,value = "教师职工号")
                                 @RequestBody List<String> list){
        QueryWrapper<Teacher> teacherQueryWrapper=new QueryWrapper<>();
        teacherQueryWrapper.in("number",list);
        List<Teacher> list1 = teacherService.list(teacherQueryWrapper);
        return Result.ok().data("list",list1);
    }


    @ApiOperation("教师登录验证")
    @PostMapping("/loginTeacher")
    public Result loginTeacher(@RequestBody Teacher teacher){
        //查询手机
        QueryWrapper<Teacher> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",teacher.getPhone());
        Teacher one = teacherService.getOne(queryWrapper);
        if (StringUtils.isEmpty(one)){
            return Result.error().message("手机号有误登录失败");
        }
        //校验密码
        if (!MD5.verify(teacher.getPassword(),one.getPassword())){
            return Result.error().message("密码有误");
        }
        //返回token
        String jwtToken = JwtUtils.getJwtToken(one.getId(), one.getName());
        return Result.ok().data("teacherToken",jwtToken).message("登录成功");
    }
}

